package com.thunder.kocho.loki;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import com.thunder.kocho.loki.builder.KeyFrameAnimatorBuilder;
import com.thunder.kocho.loki.shape.DropLoki;
import java.util.ArrayList;

/**
 * @author Hilex
 * @date 2021-3-21
 */
public class FoldingDrop extends LokiGroup {

    @Override
    protected ArrayList<Loki> onCreateChild() {
        ArrayList<Loki> lokis=new ArrayList<>();
        for(int i=0;i<4;i++){
            Loki loki=new FoldingDropLoki(i);
            loki.setAnimationDelays(0,500+i*300);
            lokis.add(loki);
        }
        return lokis;
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        super.onBoundsChange(bounds);
        bounds=clipSquare(bounds);
        float length=bounds.width()/2f;
        int cx=bounds.centerX();
        int cy=bounds.centerY();
        for(Loki loki:mLokis){
            loki.setLokiBounds((int)(cx-length/2f),bounds.top,(int)(cx+length/2f),cy);
            loki.setPivotX(cx);
            loki.setPivotY(cy);
            if(loki instanceof DropLoki){
                ((DropLoki) loki).setLeft(cx-length/2f);
                ((DropLoki) loki).setTop(bounds.top);
                ((DropLoki) loki).setLength(length);
            }
        }
    }

    @Override
    protected void onChildCreated(ArrayList<Loki> lokis) {

    }

    private static class FoldingDropLoki extends DropLoki{

        private final int index;

        public FoldingDropLoki(int index){
            this.index=index;
        }


        @Override
        protected Animator onCreateAnimator() {
            ObjectAnimator objectAnimator1=new KeyFrameAnimatorBuilder()
                    .rotate(new float[]{0f,1f},0,45+90*index)
                    .interpolator(new LinearInterpolator())
                    .duration(500)
                    .target(this)
                    .build();
             ObjectAnimator objectAnimator2=new KeyFrameAnimatorBuilder()
                     .scale(new float[]{0f,1/11f,2/11f,3/11f,4/11f,5/11f,6/11f,7/11f,8/11f,9/11f,10/11f,1f},new AccelerateDecelerateInterpolator(),1f,1f,0f,0f,0f,0f,0f,0f,1f,1f,1f,1f)
                     .count(ValueAnimator.INFINITE)
                     .interpolator(new LinearInterpolator())
                     .duration(2700)
                     .target(this)
                     .build();



            AnimatorSet animatorSet=new AnimatorSet();
            animatorSet.playTogether(objectAnimator1,objectAnimator2);
            return animatorSet;
        }
    }
}
